package org.aurora.client.spring.acquirer;

import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.aurora.client.ITaskProcessor;
import org.aurora.client.spring.SpringTaskProcessorAcquirer;
import org.springframework.context.ApplicationContext;

import java.util.Collections;
import java.util.Map;
import java.util.stream.Collectors;

public class TaskProcessorBeanSpringTaskProcessorAcquirer extends SpringTaskProcessorAcquirer {
    public TaskProcessorBeanSpringTaskProcessorAcquirer(ApplicationContext applicationContext) {
        super(applicationContext);
    }

    @Override
    public Map<String, ITaskProcessor> acquirer() {
        Map<String, ITaskProcessor> processorMap = this.applicationContext.getBeansOfType(ITaskProcessor.class);

        if (MapUtils.isEmpty(processorMap)) {
            return Collections.emptyMap();
        }

        return processorMap
                .entrySet()
                .stream()
                .collect(Collectors.toMap(
                        entry -> {
                            // 通过 ITaskProcessor#taskName 返回的任务名为空，使用 beanName
                            ITaskProcessor taskProcessor = entry.getValue();
                            String taskName = taskProcessor.taskName();

                            return StringUtils.isNotBlank(taskName) ? taskName : entry.getKey();
                        },
                        Map.Entry::getValue
                ));
    }
}
